<?php
namespace App\Service\Eticket;

use App\Models\Eticket\Activity;
use App\Repositories\Eloquent\Eticket\ActivityRepositoryEloquent;
use App\Service\Admin\BaseService;
use Exception;
use Illuminate\Support\Facades\Redis;

/**
 * 活动service
 */
class ActivityService extends BaseService
{

    private $activity;

    function __construct(ActivityRepositoryEloquent $activity)
    {
        $this->activity = $activity;
    }

    /**
     * datatables获取数据
     * @author 晚黎
     * @date   2016-11-02T10:31:46+0800
     * @return [type]                   [description]
     */
    public function ajaxIndex()
    {
        // datatables请求次数
        $draw = request('draw', 1);
        // 开始条数
        $start = request('start', config('admin.golbal.list.start'));
        // 每页显示数目
        $length = request('length', config('admin.golbal.list.length'));
        // datatables是否启用模糊搜索
        $search['regex'] = request('search.regex', false);
        // 搜索框中的值
        $search['value'] = request('search.value', '');
        // 排序
        $order['name'] = request('columns.' . request('order.0.column', 0) . '.name');
        $order['dir'] = request('order.0.dir', 'asc');

        $result = $this->activity->getActivityList($start, $length, $search, $order);

        $activities = [];

        if ($result['activities']) {
            foreach ($result['activities'] as $v) {
                $v->actionButton = $v->getActionButtonAttribute();
                //增加门票按钮
                $v->actionButton = $v->actionButton . '<a href="' . url('admin/eticket/' . $v->id . '/ticket') . '" class="btn btn-xs btn-outline btn-primary tooltips" data-original-title="门票"  data-placement="top"><i class="fa fa-ticket"></i></a> '
                    . '<a href="' . url('admin/eticket/activity/' . $v->id . '/writeOff') . '" class="btn btn-xs btn-outline btn-primary tooltips" data-original-title="核销人员"  data-placement="top"><i class="fa fa-user"></i></a> '
                    . '<a href="' . url('admin/eticket/activity/' . $v->id . '/draw') . '" class="btn btn-xs btn-outline btn-primary tooltips" data-original-title="抽奖"  data-placement="top"><i class="fa fa-gift"></i></a> ';
                $activities[] = $v;
            }
        }

        return [
            'draw' => $draw,
            'recordsTotal' => $result['count'],
            'recordsFiltered' => $result['count'],
            'data' => $activities,
        ];
    }

    /**
     * 添加活动
     * @author 晚黎
     * @date   2016-11-02T10:32:18+0800
     * @param  [type]                   $formData [表单中所有的数据]
     * @return [type]                             [true or false]
     */
    public function storeActivity($formData)
    {
        try {
            $formData['start_date'] = strtotime($formData['start_date']);
            $formData['end_date'] = strtotime($formData['end_date']);
            $formData['status'] = Activity::OPEN;
            $formData['user_id'] = getUerId();
            $result = $this->activity->create($formData);
            flash_info($result, trans('act/alert.activity.create_success'), trans('act/alert.activity.create_error'));
            return $result;
        } catch (Exception $e) {
            // 错误信息发送邮件
            $this->sendSystemErrorMail(env('MAIL_SYSTEMERROR', ''), $e);
            return false;
        }
    }

    /**
     * 根据ID获取活动数据
     * @author 晚黎
     * @date   2016-11-02T11:44:36+0800
     * @param  [type]                   $id [活动id]
     * @return [type]                       [查询出来的活动对象，查不到数据时跳转404]
     */
    public function editView($id)
    {
        $activity = $this->activity->find($id);
        if ($activity) {
            return $activity;
        }
        abort(404);
    }

    /**
     * 修改活动
     * @author 晚黎
     * @date   2016-11-02T12:45:00+0800
     * @param  [type]                   $attributes [表单数据]
     * @param  [type]                   $id         [resource路由传递过来的id]
     * @return [type]                               [true or false]
     */
    public function updateActivity($attributes, $id)
    {
        // 防止用户恶意修改表单id，如果id不一致直接跳转500
        if ($attributes['id'] != $id) {
            abort(500);
        }
        try {
            $attributes['start_grab_date'] = strtotime($attributes['start_grab_date']);
            $attributes['end_grab_date'] = strtotime($attributes['end_grab_date']);
            $attributes['start_date'] = strtotime($attributes['start_date']);
            $attributes['end_date'] = strtotime($attributes['end_date']);
            $result = $this->activity->update($attributes, $id);
            flash_info($result, trans('act/alert.activity.edit_success'), trans('act/alert.activity.edit_error'));
            return $result;
        } catch (Exception $e) {
            // 错误信息发送邮件
            $this->sendSystemErrorMail(env('MAIL_SYSTEMERROR', ''), $e);
            return false;
        }
    }

    /**
     * 活动暂不做状态管理，直接删除
     * @author 晚黎
     * @date   2016-11-02T13:23:45+0800
     * @param  [type]                   $id [活动id]
     * @return [type]                       [true or false]
     */
    public function destroyActivity($id)
    {
        try {
            $result = $this->activity->delete($id);
            flash_info($result, trans('admin/alert.activity.destroy_success'),
                trans('admin/alert.activity.destroy_error'));
            return $result;
        } catch (Exception $e) {
            // 错误信息发送邮件
            $this->sendSystemErrorMail(env('MAIL_SYSTEMERROR', ''), $e);
            return false;
        }

    }

    public function getWriteOffUsers($id)
    {
        // datatables请求次数
        $draw = request('draw', 1);
        // 开始条数
        $start = request('start', config('admin.golbal.list.start'));
        // 每页显示数目
        $length = request('length', config('admin.golbal.list.length'));
        // datatables是否启用模糊搜索
        $search['regex'] = request('search.regex', false);
        // 搜索框中的值
        $search['value'] = request('search.value', '');
        // 排序
        $order['name'] = request('columns.' . request('order.0.column', 0) . '.name');
        $order['dir'] = request('order.0.dir', 'asc');

        $openids = Redis::sMembers(Activity::cacheWriteOffUserKey($id));
        $result = [];
        foreach ($openids as $openid) {
            $result[] = [
                'openid' => $openid,
                'writeOff'=>'',
                'actionButton' => '<a href="' . url('admin/eticket/activity/' . $id . '/destroyWriteOffUser/'.$openid) . '" class="btn btn-xs btn-outline btn-danger tooltips" data-original-title="删除"  data-placement="top"><i class="fa fa-trash"></i></a> ',
            ];
        }


        return [
            'draw' => $draw,
            'recordsTotal' => count($result),
            'recordsFiltered' => count($result),
            'data' => $result,
        ];
    }
}